package cn.fl.mcr.controller;

import cmm.mid.core.framework.dto.MessageDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.condition.SysOrgQueryCondition;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.vo.AssTrailCarChannelVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrCityChannelService;
import cn.fl.mcr.transform.McrBillMVOTransform;
import cn.fl.mcr.vo.McrBillMVO;
import cn.fl.mcr.vo.McrCityChannelVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysOrgService;
import cn.fl.system.vo.SysOrgVO;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrCityChannelQC;
import cn.lionbridgecapital.loan.model.dto.McrCityChannelDTO;
import cn.lionbridgecapital.loan.model.utils.CollectionUtils;
import cn.lionbridgecapital.loan.service.api.IMcrCityChannelApiService;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 小贷账单主表 控制层
 */
@Controller
@RequestMapping("/mcr/mcrCityChannel")
public class McrCityChannelController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(McrCityChannelController.class);

    @Autowired
    private IMcrCityChannelService mcrCityChannelService;

    @Autowired
    private IMcrCityChannelApiService mcrCityChannelApiService;

    @Autowired
    private ISysOrgApiService sysOrgApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do")
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("mcr/mcrCityChannel/mcrCityChannelList");
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toAddOrgPage.do")
    public ModelAndView toAddOrgPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("mcr/mcrCityChannel/mcrCityChannelOrgList");
        String id = request.getParameter("id");
        view.addObject("id", id);
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("mcr/mcrCityChannel/mcrCityChannelAdd");
        view.addObject("id", id);
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }
    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do")
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String channelCode = request.getParameter("channelCode");
        String isValid = request.getParameter("isValid");
        Pager page = new Pager();
        McrCityChannelQC qc = new McrCityChannelQC();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        if (StringUtils.isNotEmpty(channelCode)) {
            qc.setChannelCode(channelCode);
        }
        if (StringUtils.isNotEmpty(isValid)) {
            qc.setIsValid(Integer.parseInt(isValid));
        }
        page.setCondition(qc);
        Pager pager = this.mcrCityChannelService.searchListPage(page);
        List<McrCityChannelVO> list = (List<McrCityChannelVO>) pager.getResultList();
        ListPageVO<McrCityChannelVO> listPage = new ListPageVO<McrCityChannelVO>(list, pager.getTotalCount());
        BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }


    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initOrgList.do")
    @ResponseBody
    public Object initOrgList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String id = request.getParameter("id");
        String orgNm = request.getParameter("orgNm");
        cmm.mid.core.framework.page.Pager page = new cmm.mid.core.framework.page.Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        if(StringUtils.isEmpty(id)){
            throw new BaseException("主键ID不能为空!");
        }
        McrCityChannelQC mcrCityChannelQC = new McrCityChannelQC();
        List<McrCityChannelDTO> mcrCityChannelDTOS = mcrCityChannelApiService.searchMcrCityChannelDTOList(mcrCityChannelQC);
        BaseLogUtils.info(logger, "initList", "城市放款配置.返回数据:" + JSONObject.toJSONString(mcrCityChannelDTOS), CurrentThreadContext.getCurrentUserName());
        SysOrgQueryCondition qc = new SysOrgQueryCondition();
        qc.setOrgCd("00000001");
        qc.setOrgTypCd("3");
        if (StringUtils.isNotEmpty(pageSize)) {
            qc.setOrgNm(orgNm);
        }
        if(CollectionUtils.isNotEmpty(mcrCityChannelDTOS)){
            List<String> notOrgCdS = new ArrayList<String>();
            for (McrCityChannelDTO dto : mcrCityChannelDTOS) {
                if(!dto.getId().toString().equals(id)){
                    if(StringUtils.isNotEmpty(dto.getCityCode())){
                        String[] codes = dto.getCityCode().split(",");
                        for (int i = 0; i < codes.length; i++) {
                            if(CollectionUtils.isEmpty(notOrgCdS) || !notOrgCdS.contains(codes[i])){
                                notOrgCdS.add(codes[i]);
                            }
                        }
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(notOrgCdS)){
                qc.setNotOrgCdList(notOrgCdS);
            }
        }
        page.setCondition(qc);
        cmm.mid.core.framework.page.Pager pager = this.sysOrgApiService.searchSysOrgListPage(page);
        List<SysOrgVO> list = (List<SysOrgVO>) pager.getResultList();
        ListPageVO<SysOrgVO> listPage = new ListPageVO<SysOrgVO>(list, pager.getTotalCount());
        BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do")
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        try {
            this.mcrCityChannelService.removeById(Long.valueOf(id));
            BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do")
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            McrCityChannelVO vo = this.mcrCityChannelService.selectById(Long.valueOf(id));
            if(null == vo){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
        }catch(BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch(Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do")
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response, McrCityChannelVO entity) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {
            entity.setMdfTm(new Date());
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            Long id = this.mcrCityChannelService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do")
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response, McrCityChannelVO entity) throws BaseException {
       // BaseLogUtils.info(logger, "add", "编辑城市.参数:" + JSONObject.toJSONString(request), CurrentThreadContext.getCurrentUserName());
        String idS = request.getParameter("ids");//主键ID
        //String orgNm = request.getParameter("orgNms");//主键ID
        String dataId = request.getParameter("dataId");//主键ID
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {
            String orgStr = "";
            String nmStr = "";
            JSONArray ids = JSONArray.fromObject(idS);
           // JSONArray orgNms = JSONArray.fromObject(orgNm);
            for (int i = 0; i < ids.size(); i++) {
                if (StringUtils.isNotEmpty(ids.get(i).toString())) {
                    orgStr = StringUtils.isEmpty(orgStr)?ids.get(i).toString():orgStr+","+ids.get(i).toString();
                    SysOrgDTO sysOrgDTO = this.sysOrgApiService.selectSysOrgByOrgCd(ids.get(i).toString(),"11000");
                    String orgNm = sysOrgDTO.getOrgDispNm();
                    nmStr = StringUtils.isEmpty(nmStr)?orgNm:nmStr+","+orgNm;
                }
            }
            McrCityChannelVO vo = new McrCityChannelVO();
            vo.setId(Long.valueOf(dataId));
            vo.setCityCode(orgStr);
            vo.setCityName(nmStr);
            mcrCityChannelService.modify(vo);
            BaseLogUtils.info(logger, "add", "新增数据.[ids="+ids+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

}

